package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.StringUtils;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.ContractDeal;
import com.fz.us.oa.core.service.com.BusinessChanceService;
import com.fz.us.oa.core.service.com.ContractDealService;
import com.fz.us.oa.core.service.com.CustomerInfoService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dzw on 2017/12/4.
 */
@Controller
@RequestMapping(value = "/com/contractDeal")
public class ContractDealController extends BaseController {
    private static final long serialVersionUID = -8645559752851404309L;

    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private BusinessChanceService businessChanceService;
    @Autowired
    private CustomerInfoService customerInfoService;
    @Autowired
    private ContractDealService contractDealService;

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);

        searchResult = contractDealService.paging(null,null,order,
                "com.fz.us.oa.core.entity.com.ContractDeal",
                new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);

        List<ContractDeal> contractDealList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(ContractDeal contractDeal: contractDealList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",contractDeal.getId());
            rMap.put("custName",contractDeal.getCustomerInfo()==null?"":contractDeal.getCustomerInfo().getName());
            rMap.put("contractName",contractDeal.getName());
            rMap.put("signDate", DataUtil.DateToString(contractDeal.getSignDate(),"yyyy-MM-dd"));
            rMap.put("contractMoney", contractDeal.getContractMoney());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            ContractDeal contractDeal=contractDealService.get(keyId);

            model.addAttribute("keyId", keyId);
            model.addAttribute("contractDeal", contractDeal);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/contractDeal_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            ContractDeal contractDeal=contractDealService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);

            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("contractDeal", contractDeal);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/contractDeal_read";
    }

    /**
     * 选择业务机会
     */
    @RequestMapping(value = "chooseDeal", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String chooseDeal() {
        return "/com/businessChance_dialog";
    }

    public ContractDeal setData(User user, String keyId, String customerInfoId, String name, String signDate, BigDecimal contractMoney,
                                String isHaveChance, String businessChanceId){
        ContractDeal contractDeal=null;
        if(StringUtils.isEmpty(keyId)){
            contractDeal=new ContractDeal();
            contractDeal.setCompany(user.getCompany());
        }else{
            contractDeal=contractDealService.get(keyId);
        }
        contractDeal.setCreater(user);
        contractDeal.setCustomerInfo(customerInfoService.get(customerInfoId));
        contractDeal.setName(name);
        contractDeal.setSignDate(DataUtil.StringToDate(signDate));
        contractDeal.setContractMoney(contractMoney);
        contractDeal.setIsHaveChance(isHaveChance);
        if("是".equals(isHaveChance)){
            contractDeal.setBusinessChance(businessChanceService.get(businessChanceId));
        }

        return contractDeal;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String customerInfoId, String name, String signDate, BigDecimal contractMoney,
                       String isHaveChance, String businessChanceId) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractDeal contractDeal=setData(user,keyId,customerInfoId,name,signDate,contractMoney,isHaveChance,businessChanceId);
        if(StringUtils.isNotEmpty(keyId)){
            contractDealService.update(contractDeal);
            rMap.put("message", "更新成功");
        } else {
            contractDealService.save(contractDeal, "com.fz.us.oa.core.entity.com.ContractDeal");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String customerInfoId, String name, String signDate, BigDecimal contractMoney,
                         String isHaveChance, String businessChanceId, String curDutyId, String comment) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractDeal contractDeal=setData(user,keyId,customerInfoId,name,signDate,contractMoney,isHaveChance,businessChanceId);

        if (StringUtils.isNotEmpty(keyId)) {
            contractDealService.approve(contractDeal, dutyService.get(curDutyId), comment);
        } else {
            contractDealService.commit(contractDeal, "com.fz.us.oa.core.entity.com.ContractDeal", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractDeal contractDeal=contractDealService.get(keyId);
        contractDealService.approve(contractDeal, dutyService.get(curDutyId), comment);

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //退回
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            ContractDeal contractDeal=contractDealService.get(keyId);
            contractDealService.back(contractDeal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //否决
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            ContractDeal contractDeal=contractDealService.get(keyId);
            contractDealService.deny(contractDeal, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

}
